<template>
  <div>
    <div style="position: absolute;top:10px;bottom:10px;left:10px;right:10px">
      <Card  :disHover="true">
        <Row>
          <Col :span="showAddButton?18:24">
          <div style="width:100%;">
            <slot name="searchForm"></slot>
            <!--添加搜索按钮margin-right：8px属性-->
            <Button @click="handleSearch" type="primary">搜索</Button>
            <!--<Button @click="handleReset" >重置</Button>-->
          </div>
          </Col>
          <Col :span="6" style="text-align: right" v-if="showAddButton">
          <Button  type="primary" icon="ios-create" @click="handleAdd">新建</Button>
          </Col>
        </Row>
        <!--表格区域-->
        <Row class="">
          <Table :height="tableHeight" :loading="loading" border :columns="columns" :data="data" ref="table"></Table>
        </Row>
        <Row class="page" style="margin-top: 15px">
          <Col :span="20" style="text-align: center">
          <Page :current="mmSearchFormData.pageNumber" :total="total" :page-size="mmSearchFormData.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[50,100,200]" size="small" show-total show-elevator show-sizer></Page>
          </Col>
          <Col :span="4" style="text-align: right">
          <Button icon="ios-refresh-outline" @click="handleSearch">刷新</Button>
          <Button type="info" v-show="showExport" icon="ios-download-outline" size="small">导出</Button>
          </Col>
        </Row>
      </Card>
    </div>
    <div style="position: absolute;top:100px;bottom:10px;left:10px;right:10px" ref="mainHeightDiv">
    </div>
    <Modal :title="title" v-model="modalVisible" :mask-closable='false' :width="modalWidth" style="z-index:100">
      <slot name="editForm"></slot>
      <div slot="footer">
        <slot name="leftButtons" />
        <Button  @click="cancelForm">取消</Button>
        <Button type="primary" icon="ios-paper-plane" :loading="submitLoading" @click="submitForm">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import axios from '@/libs/api.request'
  export default {
    name: 'mmTable',
    components: {
    },
    data () {
      return {
        loading:false,
        modalVisible:false,
        submitLoading:false,
        columns:[],
        total: 0,
        data: [],
        tableHeight:300,
        mmFormData:{},
        mmSearchFormData:{
          pageNumber: 1,
          pageSize: 50
        }
      };
    },
    props: {
      topHeight : {
        type: Number,
        default: 70
      },
      bottomHeight : {
        type: Number,
        default: 65
      },
      modalWidth: {
        type: Number,
        default: 500
      },
      title: {
        type: String,
        default:"编辑"
      },
      mmColumns : {
        type: Array,
        required: true
      },
      showExport : {
        type: Boolean,
        required: false
      },
      overrideFlag : {
        type: Boolean,
        default:true
      },
      autoLoad: {
        type: Boolean,
        default:true
      },
      getUrl:'',
      updateUrl:{
        type: String,
        default:""
      },
      form:{},
      formData:{},
      searchForm:{},
      searchFormData:{},
      delUrl:'',
      showColAction : {
        type: Boolean,
        default: true
      },
      showAddButton:{
        type: Boolean,
        default: true
      },
      beforSave : {
        type : Function,
        default: (res) => {
          return true
        }
      }
    },
    mounted () {
      this.init();
      window.addEventListener('resize', this.calculateHeight);
    },
    dispatch () {
      window.removeEventListener('resize', this.calculateHeight);
    },
    watch: {
      formData: function(){
        this.mmFormData = this.formData
      },
      searchFormData: function(){
//            var pageNumber = this.mmSearchFormData.pageNumber;
//            var pageSize = this.mmSearchFormData.pageSize;
        this.mmSearchFormData = this.searchFormData;
        //            console.log(this.searchFormData)
//            for (let attr in this.searchFormData) {
//                this.mmSearchFormData[attr] = this.searchFormData[attr]
//            }

      }
    },
    methods: {
      calculateHeight() {
        if(this.$refs.mainHeightDiv) {
          // this.tableHeight = this.$refs.mainHeightDiv.offsetHeight - this.topHeight - this.bottomHeight;

          this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 300;

        }
      },
      init() {
        // this.tableHeight = this.$refs.mainHeightDiv.offsetHeight - this.topHeight - this.bottomHeight;

        this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 300;

        if(this.showColAction) {
          this.columns = [...this.mmColumns,
            {
              title: "操作",
              key: "action",
              width: 200,
              align: "center",
              render: (h, params) => {
                return h("div",[h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.edit(params.row);
                      }
                    }
                  },
                  "编辑"
                ),h(
                  "Button",
                  {
                    props: {
                      type: "error",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.delete(params.row,params.index);
                      }
                    }
                  },
                  "删除"
                )])
              }
            }];
        }else{
          this.columns = [...this.mmColumns];
        }
        if(this.autoLoad){
          this.loadData()
        }
      },
      handleSearch () {
        this.loadData()
      },
      handleReset() {
        this.searchFormData.name="";
        this.loadData();
      },
      handleAdd() {
        if(this.overrideFlag){
        this.form.resetFields();
        this.formData.id = "";
        this.$emit('formDataChange', this.formData);
        this.modalVisible = true;
        }
        else{
          this.$emit('customForm');
        }
      },
      //保存新数据
      submitForm() {
        if(this.updateUrl == ''){
          this.$Message.warning("updateUrl is null");
          return false;
        }
        if(!this.beforSave()){
          return false;
        }
        this.form.validate((valid) => {
          if (valid) {

            //var formData = this.$parent.getFormData();
            var formData = this.formData;
            this.submitLoading = true;
            axios.request({
              url: this.updateUrl,
              method: 'post',
              data:formData
            }).then(res => {
              let data =res.data
              this.submitLoading = false;
              if (data.code == 200) {
                this.$Message.success("操作成功");
                this.modalVisible = false;
                this.loadData();
              }
            });
          }
        })
      },
      cancelForm() {
        this.submitLoading = false;
        this.modalVisible = false;
      },
      //初始化请求数据
      loadData() {
        this.loading = true;

        var params = this.searchFormData;
        params.pageNumber = this.mmSearchFormData.pageNumber;
        params.pageSize = this.mmSearchFormData.pageSize;

//            this.getRequest(this.getUrl, params).then(res => {
//                this.loading = false;
//                if (res.success === true) {
//                    this.data = res.result.data;
//                    this.total = res.result.totalCount;
//                }
//            });
        axios.request({
          url: this.getUrl,
          method: 'get',
          params:params
        }).then(res => {

            this.loading = false;
            let data = res.data
            if (data.code == 200) {
              this.data = data.data.data;
              this.total = data.data.totalCount;
            }
        });

      },
      changePage(p) {
        this.mmSearchFormData.pageNumber = p
        this.loadData()
      },
      changePageSize(ps) {
        this.mmSearchFormData.pageNumber = 1
        this.mmSearchFormData.pageSize = ps
        this.loadData()
      },
      //编辑按钮
      edit(row) {
        //this.$parent.getForm().resetFields();
        this.form.resetFields();

        for (let attr in row) {
          if (row[attr] === null) {
            row[attr] = "";
          }
        }
        let str = JSON.stringify(row);
        let data = JSON.parse(str);

        //this.$parent.setFormData(data)
        this.mmFormData = data

        this.$emit('formDataChange', data);

        this.modalVisible = true;
      },
      //删除按钮
      delete(row,index) {
        this.$Modal.confirm({
          title: "确认删除",
          content: "确认要删除记录?",
          onOk: () => {
            this.submitLoading = true;

//                    this.deleteRequest(this.delUrl, { id: row.id }).then(res => {
//                        this.submitLoading = false;
//                        if (res.success === true) {
//                            this.$Message.success("删除成功");
//                            this.data.splice(index,1);
//                        }
//                    });

            axios.request({
              url: this.delUrl,
              method: 'get',
              params:{ id: row.id }
            }).then(res => {
              let data =res.data
              this.submitLoading = false;
              if (data.code == 200) {
                this.$Message.success("删除成功");
                this.data.splice(index,1);
                --this.total;
              }
            });
          }
        });
      }
    }
  };
</script>
